package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.modular.system.entity.AppUserInfo;
import cn.stylefeng.guns.modular.system.entity.CashOut;
import cn.stylefeng.guns.modular.system.enums.ResultEnum;
import cn.stylefeng.guns.modular.system.exception.ProjectException;
import cn.stylefeng.guns.modular.system.service.AppCashOutService;
import cn.stylefeng.guns.modular.system.service.AppUserInfoService;
import cn.stylefeng.guns.modular.system.service.ProxyUserService;
import cn.stylefeng.guns.modular.system.utils.ResultVOUtil;
import cn.stylefeng.guns.modular.system.vo.ResultVO;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.util.MD5Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.ui.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.xml.transform.Result;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AppCashOutController
 * @Author lzy
 * @Date 2020/2/7 17:04
 * @VERSION 1.0
 **/
@Controller
@RequestMapping("/appCashOut")
public class AppCashOutController {
    private final static Logger log = LoggerFactory.getLogger(AppCashOutController.class);

    private static final String SECCESS = "SECCESS";

    private String PREFIX = "/modular/system/appCashOut/";

    @Autowired
    private AppUserInfoService appUserInfoService;

    @Autowired
    private AppCashOutService appCashOutService;

    @Autowired
    private ProxyUserService proxyUserService;
    /**
     * 跳转到主页面
     *
     * @author lzy
     * @Date 2019-06-20
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "appCashOut.html";
    }


    /**
     * 跳转驳回
     *
     * @author wg
     * @Date 2019-06-20
     */
    @RequestMapping("/turnDown")
    public String turnDown(@RequestParam("orderId") Integer orderId, Model model) {
        Assert.isTrue(!ObjectUtils.isEmpty(orderId),ResultEnum.NO_MANDATORY_FIELDS.getMessage());
        model.addAttribute("orderId",orderId);
        return PREFIX + "appCashOut_turnDown.html";
    }

    /**
     * 回显id
     * @return
     */
    @RequestMapping("/getId")
    @ResponseBody
    public ResultVO selectProxy(@RequestParam("orderId") Integer orderId){
        Assert.isTrue(!ObjectUtils.isEmpty(orderId),ResultEnum.NO_MANDATORY_FIELDS.getMessage());
        return ResultVOUtil.success(orderId);
    }

    /**
     *  分页列表
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param withdrawId
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/findCashOutAll")
    @ResponseBody
    public ResultVO findCashOutAll(@RequestParam(value = "startTime", required = false) String startTime,
                                   @RequestParam(value = "endTime", required = false)String endTime,
                                   @RequestParam(value = "withdrawId", required = false)Integer withdrawId,
                                   @RequestParam(value = "status", required = false)Integer status,
                                   @RequestParam("page")Integer pageNum, @RequestParam("limit") Integer pageSize){
        Long id = LoginContextHolder.getContext().getUserId();
        log.info("代理人id"+id);
        Assert.isTrue(!ObjectUtils.isEmpty(id), ResultEnum.PROXYID_DOES_NOT_EXIST.getMessage());
        //每个代理只能查询出自己旗下的user用户的存取款记录，不能查询出代理下面的代理的user用户
        List<String> userIds = appUserInfoService.findUserIdsByProxyId(id.toString());
        if(userIds.size() == 0){
            return ResultVOUtil.success(SECCESS);
        }
        //设置默认分页参数
        PageHelper.startPage(pageNum,pageSize);
        List<Map<Object,Object>> syss = appCashOutService.findList(startTime,endTime,withdrawId,status,userIds);
        for (Map<Object, Object> map : syss) {
            //提现金额
            BigDecimal withdrawalAmount = (BigDecimal) map.get("withdrawalAmount");
            Assert.isTrue(!ObjectUtils.isEmpty(withdrawalAmount), ResultEnum.WHATIS_SITUATION.getMessage());
            //手续费6/1000
            BigDecimal multiply = withdrawalAmount.multiply(new BigDecimal(0.006));
            map.put("handlingFee",multiply);
        }
        PageInfo<Map<Object,Object>> pageInfo = new PageInfo<>(syss);
        return ResultVOUtil.success(pageInfo.getList(),pageInfo.getTotal());
    }

    /**
     * 驳回（暂无使用）
     * @param rejectionGrounds  驳回理由
     * @param orderId   订单id
     * @return
     */
    @PostMapping("/updateTurnDown")
    @ResponseBody
    public ResultVO updateTurnDown(@RequestParam("rejectionGrounds")String  rejectionGrounds,
                                    @RequestParam("orderId")Integer orderId){
        //当前代理
        Long id = LoginContextHolder.getContext().getUserId();
        CashOut cashOut = appCashOutService.findOne(orderId);
        //如果状态不等于2并且不等于3则可以通过，否则直接返回报错
        Assert.isTrue(cashOut.getStatus() != 2 && cashOut.getStatus() != 3, ResultEnum.STATIC_EXCEPTION.getMessage());
        User user = proxyUserService.selectProxy(id);
        Assert.isTrue(!ObjectUtils.isEmpty(cashOut), ResultEnum.WITHDRAWAL_ID_DOES_NOT_EXIST.getMessage());
        cashOut.setStatus(3);
        cashOut.setDismissalHandlerId(user.getName());
        cashOut.setProcessingTime(new Date());
        cashOut.setRejectionGrounds(rejectionGrounds);

        //被驳回者用户
        AppUserInfo userInfo = appUserInfoService.selectAppUserInfo(Long.valueOf(cashOut.getUserId()));
        //回款额
        BigDecimal amountRepaid = cashOut.getMoney().multiply(new BigDecimal(0.006)).add(cashOut.getMoney());
        userInfo.setBalance(userInfo.getBalance().add(amountRepaid));
        //回滚一起执行
        appCashOutService.turnDown(cashOut,userInfo);
        return ResultVOUtil.success("SUCCESS");
    }


}
